﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Utils.Extensions
{
	public static class IListExtension
	{
		// To be used when the objects of the IList implement IComparable
		public static void Sort(this IList list)
		{
			for (int index1 = list.Count - 1; index1 >= 0; index1--)
			{
				for (int index2 = 1; index2 <= index1; index2++)
				{
					object item1 = list[index2 - 1];
					object item2 = list[index2];
					if (((IComparable)item1).CompareTo(item2) > 0)
					{
						list.Remove(item1);
						list.Insert(index2, item1);
					}
				}
			}
		}

		public static void SortDescending(this IList list)
		{
			for (int index1 = list.Count - 1; index1 >= 0; index1--)
			{
				for (int index2 = 1; index2 <= index1; index2++)
				{
					object item1 = list[index2 - 1];
					object item2 = list[index2];
					if (((IComparable)item1).CompareTo(item2) < 0)
					{
						list.Remove(item1);
						list.Insert(index2, item1);
					}
				}
			}
		}

		// To be used when we want to specify a funcion to tell how to generate from each IList item the value to compare.
		public static void Sort<TSource, TValue>(this IList<TSource> source, Func<TSource, TValue> selector)
		{
			for (int index1 = source.Count - 1; index1 >= 0; index1--)
			{
				for (int index2 = 1; index2 <= index1; index2++)
				{
					TSource item1 = source.ElementAt(index2 - 1);
					TSource item2 = source.ElementAt(index2);
					TValue valueItem1 = selector(item1);
					TValue valueItem2 = selector(item2);
					Comparer<TValue> comparer = Comparer<TValue>.Default;
					if (comparer.Compare(valueItem1, valueItem2) > 0)
					{
						source.Remove(item1);
						source.Insert(index2, item1);
					}
				}
			}
		}

		// To be used when we want to specify a funcion to tell how to generate from each IList item the value to compare.
		public static void SortDescending<TSource, TValue>(this IList<TSource> source, Func<TSource, TValue> selector)
		{
			for (int index1 = source.Count - 1; index1 >= 0; index1--)
			{
				for (int index2 = 1; index2 <= index1; index2++)
				{
					TSource item1 = source.ElementAt(index2 - 1);
					TSource item2 = source.ElementAt(index2);
					TValue valueItem1 = selector(item1);
					TValue valueItem2 = selector(item2);
					Comparer<TValue> comparer = Comparer<TValue>.Default;
					if (comparer.Compare(valueItem1, valueItem2) < 0)
					{
						source.Remove(item1);
						source.Insert(index2, item1);
					}
				}
			}
		}
	}
}

